package com.example.learnnetty.baseclass;

import com.example.learnnetty.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author ZMJ
 * @date 2020/9/21
 */
@Slf4j
public class NioDiscardClient {

    public static void startClient() throws IOException {
        InetSocketAddress address = new InetSocketAddress(CommonConstant.SOCKET_SERVER_IP, CommonConstant.SOCKET_SERVER_PORT);
        // 获得通道
        SocketChannel socketChannel = SocketChannel.open(address);
        // 切换为非阻塞模式
        socketChannel.configureBlocking(false);
        // 不断的自旋，等待连接完成，或者做一些其他的事情
        while (!socketChannel.finishConnect()) {
            log.info("不断的自旋，等待连接完成，或者做一些其他的事情");
        }
        log.info("客户端连接成功");
        // 分配指定大小的缓存区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put("hello word".getBytes());
        byteBuffer.flip();
        // 发送到服务器
        socketChannel.write(byteBuffer);
        socketChannel.shutdownOutput();
        socketChannel.close();

    }

    public static void main(String[] args) throws IOException {
        startClient();
    }

}
